//
//  LJLournal.m
//  LJClientKit
//
//  Created by che on 12/7/09.
//  Copyright 2009 AntonChebotaev. All rights reserved.
//

#import "LJJournal.h"

// Exceptions
NSString * const LJJournalBadInitException = @"LJJournalBadInitException";

@implementation LJJournal

#pragma mark Properties
@synthesize name;
@synthesize account;
@synthesize tags;

#pragma mark Lifecycle
- (id)init {
	[self dealloc];
    @throw [NSException exceptionWithName:LJJournalBadInitException
								   reason:@"Initialize LJAccount without username"
								 userInfo:nil];
    return nil;	
}

- (id)initWithName:(NSString *)aName andAccount:(LJAccount *)anAccount {
	self = [super init];
	if (self) {
        name = [aName retain];
        account = anAccount;
		tags = [[NSMutableSet alloc] init];
    }
    return self;
}

- (void)dealloc {
	[name release];
	[tags release];
	[super dealloc];
}

#pragma mark NSCoding implementation
- (id)initWithCoder:(NSCoder *)decoder {
	self = [super init];
    if (self) {
        name = [[decoder decodeObjectForKey:@"LJJournalCodingName"] retain];
		tags = [[decoder decodeObjectForKey:@"LJJournalCodingTags"] retain];
        account = [decoder decodeObjectForKey:@"LJJournalCodingAccountReference"];

        NSAssert(account != nil, @"LJJournal decoded without an account object.");
        NSAssert(name != nil, @"LJJournal decoded without a name.");
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:name forKey:@"LJJournalCodingName"];
	[encoder encodeObject:tags forKey:@"LJJournalCodingTags"];
	[encoder encodeConditionalObject:account forKey:@"LJJournalCodingAccountReference"];
}

#pragma mark Methods
+ (id)journalWithName:(NSString *)aName andAccount:(LJAccount *)anAccount {
	LJJournal * journal = [[LJJournal alloc] initWithName:aName andAccount:anAccount];
	return [journal autorelease];
}

- (BOOL)isDefault {
	return [name isEqual:[account username]];
}

- (void)addTag:(LJTag *)newTag {
	[tags addObject:newTag];
}

#pragma mark NSObject overloads
- (NSString *)description {
	return [NSString stringWithFormat:@"%@ by %@", name, [account description]];
}

- (NSUInteger)hash {
	return [[self description] hash];
}

- (BOOL)isEqual:(id)object {
	return [object isMemberOfClass:[LJJournal class]] && [[self description] isEqual:[object description]];
}

@end
